import os
import sys 
import pymysql
import shutil
import datetime
import json
import subprocess

def llz_backup():

     # 备份目标文件夹路径
    db_config_folder = 'D:\py\lz\web\config'
    with open(os.path.join(db_config_folder,'db_back.config'),'r',encoding='utf-8') as f:
        config=json.load(f)

    # MySQL数据库连接配置
    host = config['host']
    user = config['user']
    password = config['password']
    database =config['database'] 
    port=config['port']


   
    # 获取当前日期和时间
    current_datetime = datetime.datetime.now()
    timestamp = current_datetime.strftime('%Y%m%d%H%M%S')

    # 连接MySQL数据库

    connection = pymysql.connect(
            host=host,       # 数据库主机地址
            user=user,     # 数据库用户名
            password=password,# 数据库密码
            database=database,  # 要连接的数据库名称
            port=port
        )


    try:
        # 创建游标对象
        cursor = connection.cursor()

        # 执行备份命令
        backup_folder=config['back_folder']
        backup_file = f"{backup_folder}/{timestamp}_llz_sqlback.sql"

        # 执行备份命令
        backup_command=f"mysqldump -u {user} -p{password} {database} > {backup_file}"
        subprocess.call(backup_command, shell=True)

        # 关闭游标
        cursor.close()

        # 备份完成后可以执行其他操作，例如打印成功消息
        print("MySQL备份成功")

    finally:
        # 关闭数据库连接
        connection.close()
    



if __name__=='__main__':
    llz_backup()